package jkoa.middleware;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import jkoa.core.Context;
import jkoa.core.Middleware;
import jkoa.core.Next;
import jkoa.core.Request;
import jkoa.core.Response;

public class HttpServerMiddleware implements Middleware {

	private RouterMiddleware router;
	private int port;

	public HttpServerMiddleware(RouterMiddleware router, int port) {
		this.router = router;
		this.port = port;
	}

	public void start() {
		try (ServerSocket serverSocket = new ServerSocket(port)) {
			System.out.println("Server started on port " + port);
			while (true) {
				Socket clientSocket = serverSocket.accept();
				handleRequest(clientSocket);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void handleRequest(Socket clientSocket) {
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
				PrintWriter writer = new PrintWriter(clientSocket.getOutputStream())) {
			String requestLine = reader.readLine();
			if (requestLine != null) {
				String[] parts = requestLine.split(" ");
				String method = parts[0];
				String path = parts[1];
				Context ctx = new Context(new Request(method, path), new Response());
				router.handleRequest(method, path, ctx);
			}
			clientSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void handle(Context ctx, Next next) {
		// TODO Auto-generated method stub
		
	}
}
